package com.example.mallorder.impl;

import com.example.mallcommon.RestResult;
import com.example.mallorder.api.dao.OrderDao;
import com.example.mallorder.api.domain.Order;
import com.example.mallorder.api.service.OrderService;
import com.example.mallproduct.api.domain.Product;
import com.example.mallproduct.feign.ProductFeign;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/** @author yangtao */
@Service
public class OrderServiceImpl implements OrderService {
  @Autowired private OrderDao orderDao;
  @Autowired private ProductFeign productFeign;
  @Autowired private RocketMQTemplate rocketMQTemplate;


  /**
   * seata 加入全局事务控制GlobalTransactional
   * @param pid
   * @return
   */
  @Override
  // @GlobalTransactional(rollbackFor = Exception.class)
  public Order createOrder(Integer pid) {
    // 调用商品微服务,查询商品信息
    RestResult<Product> byPid = productFeign.findByPid(pid);
    Product product = byPid.getData();
    if (product.getPid() == -1) {
      Order order = new Order();
      order.setPname("下单失败");
      return order;
    }
    // 下单(创建订单)
    Order order = new Order();
    order.setUid(1);
    order.setUsername("测试用户");
    order.setPid(pid);
    order.setPname(product.getPname());
    order.setPprice(product.getPprice());
    order.setNumber(1);
    orderDao.insert(order);
    // 3 扣库存
    productFeign.reduceInventory(pid, order.getNumber());
    // 下单成功之后,将消息放到mq中
    rocketMQTemplate.convertAndSend("order-topic", order);
    return order;
  }
}
